import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(TreeNode left,int val, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class LeetCode102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        //创建一个队列
        LinkedList<TreeNode> queue = new LinkedList<>();
        //向队列尾插入值
        queue.offer(root);
        int c1 = 1;//用于记录当前根节点
        //循环判断队列到为空结束
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int c2 = 0; // 用于记录下一层的节点数量
            //用于记录根节点的左子节点 右子节点
            for (int i = 0; i < c1; i++) {
                //从对列头获取值, 并移除
                TreeNode node = queue.poll();
                list.add(node.val);
                //判断当前根节点 是否有左子节点 右子节点
                if (node.left != null) {
                    //有的话，添加到队列中
                    queue.offer(node.left);
                    c2++;
                }
                if(node.right != null){
                    queue.offer(node.right);
                    c2++;
                }

            }
            result.add(list);
            c1 = c2;
        }
        return result;
    }
}

